import { forwardRef, useEffect, useState } from 'react';
import { DataType } from '../../type';
import { Table, TableColumnsType } from 'antd';
import { i18n, removeEmptyArrays } from '@/common/utils';
import { useDocumentStore } from '@/common/store';
import styles from './styles.module.scss';
type Props = {
  onContextMenu: (record: DataType, event: React.MouseEvent) => void;
};
export const TableTree = forwardRef<any, Props>(({ onContextMenu }, ref) => {
  const [selectKey, setSelectKey] = useState('');
  const { databaseInfo } = useDocumentStore();
  const [databaseList, setDatabaseList] = useState([]);
  const [tableHeight, setTableHeight] = useState(0); // details主表格高度
  const onResizeTop = () => {
    const box = document.querySelector('.panel_top')?.getBoundingClientRect();
    const head = document
      .querySelector('.panel_top .ant-table-header')
      ?.getBoundingClientRect();
    setTableHeight(box?.height - (head?.height ?? 36));
  };
  useEffect(() => {
    onResizeTop();
  }, []);
  // 表格列字段
  const columns: TableColumnsType<DataType> = [
    {
      title: '名称',
      dataIndex: 'label',
      key: 'label',
      width: '40%',
      ellipsis: true,
      // 根据 visibleColumns 中的值决定列是否展示
      render: (text, record) => {
        const isParent = record.children && record.children.length > 0;
        text = i18n.t(`database.${text}`, { defaultValue: text });
        return isParent ? <strong>{text}</strong> : text;
      },
    },
  ];
  useEffect(() => {
    if (databaseInfo?.objects) {
      setDatabaseList(removeEmptyArrays(databaseInfo.objects));
    }
  }, [databaseInfo]);
  return (
    <>
      {databaseList.length ? (
        <Table<DataType>
          ref={ref}
          columns={columns}
          // rowSelection={{ ...rowSelection, checkStrictly: false }}
          dataSource={databaseList}
          scroll={{ y: tableHeight }}
          onRow={(record) => ({
            onClick: () => {
              setSelectKey(record.dxid);
              // const parentNode = findParentNodes(databaseList, record.name);
              // if (parentNode) {
              //   handleRowClick(record, parentNode);
              //   handleParentNodeChange(parentNode?.rootParent?.name);
              //   nmAppLog('所属父节点:', parentNode, record);
              // }
            },
            onContextMenu: (event) => onContextMenu(record, event),
          })}
          rowClassName={(record: any) =>
            selectKey === record.dxid ? styles['selected-row'] : ''
          }
          size='small'
          rowKey='dxid'
          pagination={false}
          expandable={{
            defaultExpandAllRows: true, // 默认展开所有行
          }}
        />
      ) : (
        ''
      )}
    </>
  );
});
